package cn.yotta.user.core.web.utils;

import cn.yotta.common.api.model.ApiRequest;
import cn.yotta.common.api.model.CheckValid;
import cn.yotta.user.web.autoconfiguration.context.tenant.TenantContext;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author wyaoyao
 * @date 2022/11/8 17:36
 */
@UtilityClass
@Slf4j
public class ApiExecutor {

    public static <T extends ApiRequest, R> R execute(Function<T, R> function, T t) {
        wrapperTenant(t);
        t.checkValid();
        return function.apply(t);
    }


    public static <T extends CheckValid, R> R execute(Function<T, R> function, T t) {
        t.checkValid();
        return function.apply(t);
    }

    private static void wrapperTenant(ApiRequest request) {
        request.setTenantId(TenantContext.getTenantId());
    }

    public static <T> T execute(Supplier<T> supplier) {
        return supplier.get();
    }

}
